package persistence.mysql;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3Demo.OkHttpClientFactory;
import persistence.common.ConnectionProperties;
import utils.StringUtils;

import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MysqlConnection {
    //jdbc:mysql://localhost:3306/shopping?user=root&password=&useUnicode=true&characterEncoding=utf-8
    private static final String url_format = "jdbc:mysql://%s:%s/%s?user=%s&password=%s&useUnicode=true&characterEncoding=utf-8";
    public static Connection getConnection(ConnectionProperties properties){
        String url = String.format(url_format
                , properties.getServer()
                , properties.getPort()
                , properties.getDatabase()
                , properties.getUsername()
                , properties.getPassword()
        );
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url);
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        ConnectionProperties properties = new ConnectionProperties();
        properties.setServer("localhost");
        properties.setPort(3306);
        properties.setDatabase("data");
        properties.setUsername("root");
        properties.setPassword("");


        String hello = "'hello'";
        System.out.println(handerStr(hello));

    }

    public static String handerStr(String source){
        if(StringUtils.isNullOrEmpty(source))return source;
        return source.replaceAll("\'","\\\\'");
    }
}
